package com.homelock.service;

import com.homelock.common.util.CGlibMapper;
import com.homelock.common.util.DateUtils;
import com.homelock.common.vo.PageResp;
import com.homelock.common.vo.Resp;
import com.homelock.domain.query.ComHouseholdQuery;
import com.homelock.entity.*;
import com.homelock.mapper.HlCommunityHouseholdMapper;
import com.homelock.mapper.HlCommunitySmsMapper;
import com.homelock.mapper.HlCommunitySmsRecordMapper;
import com.homelock.vo.HouseholdVO;
import com.pi.base.enumerate.record.RecordState;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class HlCommunityHouseholdService {
    private static final Logger logger = LoggerFactory.getLogger(HlCommunityHouseholdService.class);

    @Autowired
    HlCommunityHouseholdMapper hlCommunityHouseholdMapper;
    @Autowired
    HlCommunitySmsMapper hlCommunitySmsMapper;
    @Autowired
    HlCommunitySmsRecordMapper hlCommunitySmsRecordMapper;

    public HlCommunityHousehold queryByCommunityIdAndContact(Long communityId,String contact){
        HlCommunityHouseholdExample example = new HlCommunityHouseholdExample();
        example.createCriteria().andCommunityIdEqualTo(communityId).
                andHouseholdContactEqualTo(contact).
                andStateEqualTo(RecordState.STATE_NORMAL.getState());
        List<HlCommunityHousehold> list = hlCommunityHouseholdMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        return list.get(0);
    }

    public Resp insert(Long communityId,String householdName,String householdContact,String address){
        HlCommunityHousehold household = queryByCommunityIdAndContact(communityId,householdContact.trim());
        if(household != null){
            return Resp.faild("住户电话已经存在",null);
        }
        HlCommunityHousehold hlCommunityHousehold = new HlCommunityHousehold();
        hlCommunityHousehold.setCommunityId(communityId);
        Date now = new Date();
        hlCommunityHousehold.setCreateDate(now);
        hlCommunityHousehold.setUpdateDate(now);
        hlCommunityHousehold.setState(RecordState.STATE_NORMAL.getState());
        hlCommunityHousehold.setHouseholdContact(householdContact.trim());
        hlCommunityHousehold.setHouseholdName(householdName.trim());
        hlCommunityHousehold.setAddress(StringUtils.trimToEmpty(address));
        hlCommunityHousehold.setVersion(1L);
        hlCommunityHouseholdMapper.insertSelective(hlCommunityHousehold);
        return Resp.ok();
    }

    public Resp update(Long id, String householdName, String householdContact,String address){
        address = StringUtils.trimToEmpty(address);
        HlCommunityHousehold hlCommunityHousehold = hlCommunityHouseholdMapper.selectByPrimaryKey(id);
        if(hlCommunityHousehold == null || hlCommunityHousehold.getState() != RecordState.STATE_NORMAL.getState()){
            return Resp.faild("住户信息不存在",null);
        }
        if(hlCommunityHousehold.getHouseholdContact().equals(householdContact.trim()) &&
         hlCommunityHousehold.getHouseholdName().equals(householdName.trim())){
            if(hlCommunityHousehold.getAddress().equals(address)){
                // 无修改则不数据库更新
                return Resp.ok();
            }
        }
        // 电话修改之后 需要check是否重复
        if(!hlCommunityHousehold.getHouseholdContact().equals(householdContact.trim())){
            HlCommunityHousehold sameContact = queryByCommunityIdAndContact(hlCommunityHousehold.getCommunityId(),householdContact);
            if(sameContact != null){
                return Resp.faild("住户电话已经存在");
            }
        }
        hlCommunityHousehold.setHouseholdName(householdName.trim());
        hlCommunityHousehold.setHouseholdContact(householdContact.trim());
        hlCommunityHousehold.setUpdateDate(new Date());
        hlCommunityHousehold.setVersion(hlCommunityHousehold.getVersion()+1);
        hlCommunityHousehold.setAddress(address);
        hlCommunityHouseholdMapper.updateByPrimaryKey(hlCommunityHousehold);
        return Resp.ok();
    }

    public boolean delete(Long id){
        HlCommunityHousehold hlCommunityHousehold = hlCommunityHouseholdMapper.selectByPrimaryKey(id);
        if(hlCommunityHousehold == null ||hlCommunityHousehold.getState() == RecordState.STATE_DELETE.getState()){
            return true;
        }
        hlCommunityHousehold.setState(RecordState.STATE_DELETE.getState());
        hlCommunityHousehold.setUpdateDate(new Date());
        hlCommunityHousehold.setVersion(hlCommunityHousehold.getVersion()+1);
        return hlCommunityHouseholdMapper.updateByPrimaryKey(hlCommunityHousehold) > 0;
    }


    /**
     * 批量删除
     * @param ids
     * @return
     */
    public boolean deleteByIds(List<Long> ids){
        if(CollectionUtils.isEmpty(ids)){
            return true;
        }
        for(Long id:ids){
            delete(id);
        }
        return true;
    }

    public PageResp queryPageHousehold(ComHouseholdQuery query){
        HlCommunityHouseholdExample example = new HlCommunityHouseholdExample();
        HlCommunityHouseholdExample.Criteria criteria = example.createCriteria();
        criteria.andStateEqualTo(RecordState.STATE_NORMAL.getState());
        if(query.getCommunityId() != null){
            criteria.andCommunityIdEqualTo(query.getCommunityId());
        }
        if(StringUtils.isNotBlank(query.getHouseholdName())){
            criteria.andHouseholdNameLike("%"+query.getHouseholdName()+"%");
        }
        if(StringUtils.isNotBlank(query.getHouseholdContact())){
            criteria.andHouseholdContactLike("%"+query.getHouseholdContact()+"%");
        }
        if(StringUtils.isNotBlank(query.getAddress())){
            criteria.andAddressLike("%"+query.getAddress()+"%");
        }
        if( query.getLimit() != null && query.getOffset() != null){
            example.setOrderByClause(" id desc limit "+query.getOffset()+" , "+query.getLimit()+" ");
        }
        List<HlCommunityHousehold> list = hlCommunityHouseholdMapper.selectByExample(example);
        List<HouseholdVO> result;
        if(!CollectionUtils.isEmpty(list)){
            result = new ArrayList<>(list.size());
            for (HlCommunityHousehold item:list){
                HouseholdVO householdVO = CGlibMapper.mapper(item,HouseholdVO.class);
                householdVO.setCreateTime(DateUtils.date2String(householdVO.getCreateDate(),DateUtils.ISO_DATETIME_FORMAT));
                result.add(householdVO);
            }
        }else{
            result = new ArrayList<>(0);
        }
        int count = hlCommunityHouseholdMapper.countByExample(example);
        return new PageResp(result,count);
    }


    public List<String> queryPhoneByCommunityIdAndIds(Long communityId,List<Long> ids){
        HlCommunityHouseholdExample example = new HlCommunityHouseholdExample();
        example.createCriteria().andCommunityIdEqualTo(communityId).andIdIn(ids).andStateEqualTo(RecordState.STATE_NORMAL.getState());
        List<HlCommunityHousehold> list = hlCommunityHouseholdMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        List<String> phonelist = list.stream().map(HlCommunityHousehold::getHouseholdContact).collect(Collectors.toList());
        return phonelist;
    }


    public Integer querySmsSendNumByCommunityId(Long communityId){
        HlCommunitySms sms = querySmsSendByCommunityId(communityId);
        return sms == null ? 0 : sms.getSmsnumMax();
    }

    public HlCommunitySms querySmsSendByCommunityId(Long communityId){
        HlCommunitySmsExample hlCommunitySmsExample = new HlCommunitySmsExample();
        hlCommunitySmsExample.createCriteria().andCommunityIdEqualTo(communityId).andStateEqualTo(RecordState.STATE_NORMAL.getState());
        List<HlCommunitySms> list = hlCommunitySmsMapper.selectByExample(hlCommunitySmsExample);
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        return list.get(0);
    }

    public void insertOrUpdateSmsSendNum(Long communityId,Integer sendNum){
        if(sendNum == null){
            sendNum = 0;
        }
        HlCommunitySms sms = querySmsSendByCommunityId(communityId);
        Date current = new Date();
        if(sms == null){
            sms = new HlCommunitySms();
            sms.setCommunityId(communityId);
            sms.setCreateDate(current);
            sms.setVersion(1L);
            sms.setSmsnumMax(sendNum);
            sms.setState(RecordState.STATE_NORMAL.getState());
            sms.setUpdateDate(current);
            hlCommunitySmsMapper.insert(sms);
        }else{
            if(sendNum.intValue() == sms.getSmsnumMax().intValue()){
                return;
            }
            sms.setSmsnumMax(sendNum);
            sms.setUpdateDate(current);
            sms.setVersion(sms.getVersion()+1);
            hlCommunitySmsMapper.updateByPrimaryKey(sms);
        }
    }

    /**
     * 插入sms发送记录
     * @param hlCommunitySmsRecord
     */
    public void insertSmsSendRecord(HlCommunitySmsRecord hlCommunitySmsRecord){
        Date current = new Date();
        hlCommunitySmsRecord.setCreateDate(current);
        hlCommunitySmsRecord.setVersion(1L);
        hlCommunitySmsRecord.setState(RecordState.STATE_NORMAL.getState());
        hlCommunitySmsRecord.setUpdateDate(current);
        hlCommunitySmsRecordMapper.insert(hlCommunitySmsRecord);
    }
}

